<%@page import="java.text.Format"%>
<%@page import="java.util.Formatter"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.google.appengine.api.datastore.Query.SortDirection"%>
<%@page import="java.util.Date"%>
<%@page import="com.google.appengine.api.datastore.Query.FilterOperator"%>
<%@page import="java.util.Arrays"%>
<%@page import="com.google.appengine.api.datastore.PreparedQuery"%>
<%@page import="com.google.appengine.api.datastore.FetchOptions"%>
<%@page import="com.google.appengine.api.datastore.Query"%>
<%@page import="com.google.appengine.api.users.UserService"%>
<%@page import="com.google.appengine.api.users.UserServiceFactory"%>
<%@page import="com.google.appengine.api.datastore.DatastoreService"%>
<%@page
	import="com.google.appengine.api.datastore.DatastoreServiceFactory"%>
<%@page import="com.google.appengine.api.datastore.Entity"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="org.gmapschallenge.GmcServlet"%>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<%
	final String[] adminz = new String[] { "me@destil.cz", "bart@bartweb.cz", "varkockova.a@gmail.com" };
	final List<String> admins = Arrays.asList(adminz);
	UserService userService = UserServiceFactory.getUserService();
	String thisURL = request.getRequestURI();
	boolean signedIn = false;
	boolean registered = false;
	String currentUser = "";
	String logoutUrl = "";
	String loginUrl = "";
	String success = null;
	String error = null;
	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	if (request.getUserPrincipal() != null) {
		currentUser = request.getUserPrincipal().getName().trim().toLowerCase();
		logoutUrl = userService.createLogoutURL(thisURL);
		signedIn = true;
		// is user registered?
		Query query = new Query("Participant");
		query.addFilter("email", FilterOperator.EQUAL, currentUser);
		PreparedQuery pq = datastore.prepare(query);
		Entity userEntity = pq.asSingleEntity();
		if (userEntity != null) {
			registered = true;
		}

		// add points when qr found
		if (registered && request.getParameter("c") != null) {
			String code = request.getParameter("c");
			query = new Query("Code");
			query.addFilter("code", FilterOperator.EQUAL, code);
			pq = datastore.prepare(query);
			Entity entity = pq.asSingleEntity();
			if (entity == null) {
				error = "Neexistující QR kód";
			} else {
				int points = Integer.parseInt((String) entity.getProperty("points"));
				long number = (Long) entity.getProperty("number");
				query = new Query("Find");
				query.addFilter("code", FilterOperator.EQUAL, code);
				query.addFilter("participant", FilterOperator.EQUAL, currentUser);
				pq = datastore.prepare(query);
				int count = pq.countEntities(FetchOptions.Builder.withLimit(1));
				if (count > 0) {
					error = "Tento QR kód už jsi scanoval";
				} else {
					// FTF
					query = new Query("Find");
					query.addFilter("code", FilterOperator.EQUAL, code);
					pq = datastore.prepare(query);
					count = pq.countEntities(FetchOptions.Builder.withLimit(1));
					boolean ftf;
					if (count == 0) {
						points += Math.round((double) 0.5 * (double) points);
						success = "Jsi tady první!!! Za to je bonus 50%, takže získáváš " + points + " bodů";
						ftf = true;
					} else {
						success = "Za tento nález získáváš " + points + " bodů!";
						ftf = false;
					}
					// save to db
					entity = new Entity("Find");
					entity.setProperty("number", number);
					entity.setProperty("code", code);
					entity.setProperty("participant", currentUser);
					entity.setProperty("found", new Date());
					entity.setProperty("user_agent", request.getHeader("User-Agent"));
					entity.setProperty("ftf", ftf);
					entity.setProperty("points", points);
					datastore.put(entity);
					userEntity.setProperty("score", ((Long) userEntity.getProperty("score") + points));
					datastore.put(userEntity);
				}
			}
		}

		// add shout
		if (registered && request.getParameter("message") != null) {
			Entity entity = new Entity("Shout");
			entity.setProperty("shouted", new Date());
			entity.setProperty("message", (String) request.getParameter("message"));
			entity.setProperty("participant", currentUser);
			datastore.put(entity);
		}

		// add users to database - only for admins
		if (request.getParameter("participants") != null && admins.contains(currentUser)) {
			String participants = request.getParameter("participants");
			String[] emails = participants.split(" ");
			List<Entity> entities = new ArrayList<Entity>();
			for (String email : emails) {
				Entity entity = new Entity("Participant");
				entity.setProperty("email", email);
				entity.setProperty("score", 0);
				entities.add(entity);
			}
			datastore.put(entities);
			success = "Lidičky byli přidáni";
		}
		// add QR code to database - only for admins
		if (request.getParameter("points") != null && admins.contains(currentUser)) {
			query = new Query("Code");
			pq = datastore.prepare(query);
			int count = pq.countEntities(FetchOptions.Builder.withLimit(500));

			Entity entity = new Entity("Code");
			entity.setProperty("lat", request.getParameter("lat"));
			entity.setProperty("lon", request.getParameter("lon"));
			entity.setProperty("points", request.getParameter("points"));
			entity.setProperty("code", request.getParameter("code"));
			entity.setProperty("number", count + 1);
			datastore.put(entity);
			success = "QR kód byl přidán, mapa aktualizována.";
		}
	} else {
		loginUrl = userService.createLoginURL(thisURL);
	}
%>
<!DOCTYPE html>

<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]>    <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]>    <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!-->
<html lang="cs" itemscope itemtype="http://schema.org/Event">
<!--<![endif]-->
<head>
<meta charset="utf-8" />

<!-- Set the viewport width to device width for mobile -->
<meta name="viewport" content="width=device-width" />
<meta itemprop="name" content="Google Maps Challenge">
<meta itemprop="description"
	content="Geolokační hra 14.3.2012 #gmapschallenge #gugcz">
<meta itemprop="image"
	content="http://gmapschallenge.appspot.com/images/logo.png">

<title>Google Maps Challenge</title>

<!-- Included CSS Files -->
<link rel="stylesheet" href="stylesheets/foundation.css">
<link rel="stylesheet" href="stylesheets/app.css">
<link rel="shortcut icon" href="favicon.ico" />

<!--[if lt IE 9]>
		<link rel="stylesheet" href="stylesheets/ie.css">
	<![endif]-->


<!-- IE Fix for HTML5 Tags -->
<!--[if lt IE 9]>
		<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->

</head>
<body>

	<!-- container -->
	<div class="container">

		<div class="row">
			<div class="eight columns">
				<a href="/"><h3>Google Maps Challenge</h3></a>
			</div>
			<div class="four columns text-center">
				<%
					if (signedIn) {
				%><div style="margin-top: 10px"><%=GmcServlet.formatMail(currentUser)%>
					<a href="<%=logoutUrl%>">Logout</a>
				</div>
				<%
					} else {
				%>
				<a href="<%=loginUrl%>"><img src="images/sign_with_google.png"
					alt="Sign In with Google" /></a>
				<%
					}
				%>
			</div>
			<hr />
		</div>
		<div class="row">
			<%
				if (signedIn && registered) {
					String q = request.getQueryString();
					String include = "home.jsp";
					if (q != null) {
						if (q.startsWith("c")) {
							include = "code.jsp";
						} else if (q.startsWith("add")) {
							include = "add.jsp";
						} else if (q.startsWith("save")) {
							include = "save.jsp";
						}
					}
			%><div class="four columns">
				<%
					if (success != null) {
							out.println("<div class=\"alert-box success\">" + success + "</div>");
						}
						if (error != null) {
							out.println("<div class=\"alert-box error\">" + error + "</div>");
						}
				%>
				<jsp:include page='<%=include%>' />
			</div>
			<div class="four columns">
				<h4>Leaderboard</h4>
				<table>
					<%
						Query query = new Query("Participant");
							query.addSort("score", SortDirection.DESCENDING);
							PreparedQuery pq = datastore.prepare(query);
							List<Entity> participants = pq.asList(FetchOptions.Builder.withLimit(100));
							int i = 1;
							for (Entity participant : participants) {
								String email = (String) participant.getProperty("email");
								String me = "";
								if (email.equals(currentUser)) {
									me = " class=\"me\"";
								}
								out.println("<tr" + me + "><td>" + i + ".</td><td>" + GmcServlet.formatMail(email) + "</td><td>"
										+ participant.getProperty("score") + " bodů</td></tr>");
								i++;
							}
					%>
				</table>
			</div>
			<div class="four columns">
				<h4>Shoutbox</h4>
				<form method="post">
					<p>Napište něco ostatním účastníkům nebo organizátorům:</p>
					<textarea rows="2" cols="30" name="message"></textarea>
					<input type="submit" value="Shout" />
				</form>
				<table>
					<%
						query = new Query("Shout");
							query.addSort("shouted", SortDirection.DESCENDING);
							pq = datastore.prepare(query);
							List<Entity> shouts = pq.asList(FetchOptions.Builder.withLimit(20));
							for (Entity shout : shouts) {
								Format formatter = new SimpleDateFormat("HH:mm:ss");
								String shouted = formatter.format((Date) shout.getProperty("shouted"));
								String participant = (String) shout.getProperty("participant");
								if (admins.contains(participant)) {
									participant = "<font color=\"#f68b01\">Organizátor</font>";
								} else {
									participant = GmcServlet.formatMail(participant);
								}
								String message = (String) shout.getProperty("message");
								out.println("<tr><td>" + participant + "<br />" + shouted + "</td><td>" + message + "</td></tr>");
							}
					%>
				</table>
			</div>

			<%
				} else if (!signedIn) {
			%><div class="twelve columns text-center">
				<div class="alert-box warning">Přihlas se tvým Google účtem</div>
			</div>
			<%
				} else {
			%><div class="twelve columns text-center">
				<div class="alert-box error">Tvůj účet není registrován v
					soutěži. Běž za Destilem, aby tě tam přidal.</div>
			</div>
			<%
				}
			%>
			<br />
			<hr />
		</div>
		<div class="row">
			<div class="six columns text-center">
				<p>
					Sdílejte zážitky z akce s hashtagem <strong>#gmapschallenge</strong>:
				</p>

				<!-- Place this tag where you want the +1 button to render -->
				<g:plusone size="medium" annotation="none"
					href="http://gmapschallenge.appspot.com/"></g:plusone>
				&nbsp;&nbsp;&nbsp;

				<!-- Place this render call where appropriate -->
				<script type="text/javascript">
  window.___gcfg = {lang: 'cs'};

  (function() {
    var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
    po.src = 'https://apis.google.com/js/plusone.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
  })();
</script>

				<a
					href="https://twitter.com/intent/tweet?button_hashtag=gmapschallenge"
					class="twitter-hashtag-button" data-related="destil">Tweet
					#gmapschallenge</a>
				<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
			</div>
			<div class="six columns text-center">
				Připravil <a
					href="https://plus.google.com/100156589101321820776/about"
					rel="author">Destil</a>, kód tohoto systému je <a href="https://code.google.com/p/google-maps-challenge/">open-source</a>.<br />
				<br />
			</div>
		</div>
	</div>
	<!-- container -->

	<!-- Included JS Files 
	<script src="javascripts/jquery.min.js"></script>
	<script src="javascripts/modernizr.foundation.js"></script>
	<script src="javascripts/foundation.js"></script>
	<script src="javascripts/app.js"></script>-->

</body>
</html>
